package com.fx.zmlzml.controller;

import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcCooler;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcCoolerService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑散热器 Controller
 * 提供RESTful API接口，用于操作电脑散热器数据
 */
@RestController
@RequestMapping("/api/cooler")
@Tag(name = "电脑散热器管理", description = "提供电脑散热器的CRUD操作及相关查询功能")
public class PcCoolerController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcCoolerController.class);
    
    @Autowired
    private PcCoolerService pcCoolerService;
    
    /**
     * 分页获取电脑散热器列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取电脑散热器列表", description = "分页查询系统中的电脑散热器信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcCooler>> getPcCoolersByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑散热器请求，页码：{}，每页大小：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum < 1 || pageSize < 1) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.page_num") + "，" + 
                        MessageUtils.getMessage("common.validation.page_size"));
            }

            PageHelper.startPage(pageNum, pageSize);
            List<PcCooler> list = pcCoolerService.list();
            PageInfo<PcCooler> pageInfo = new PageInfo<>(list);

            logger.info("分页查询电脑散热器成功，总数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "cooler.query.success", null);
        } catch (Exception e) {
            logger.error("分页查询电脑散热器异常", e);
            return Result.error(MessageUtils.getMessage("error.query"));
        }
    }
    
    /**
     * 根据ID获取电脑散热器信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取电脑散热器信息", description = "根据ID查询指定的电脑散热器详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到数据", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcCooler> getPcCoolerById(
            @Parameter(description = "电脑散热器ID", required = true, example = "1") @PathVariable Long id) {
        logger.info("根据ID查询电脑散热器请求，ID：{}", id);
        try {
            PcCooler cooler = pcCoolerService.getById(id);
            if (cooler == null) {
                logger.warn("未找到ID为{}的电脑散热器", id);
                return Result.error(ErrorEnum.RESOURCE_NOT_FOUND.getCode(), MessageUtils.getMessage("error.notFound"));
            }
            logger.info("根据ID查询电脑散热器成功");
            return Result.success(cooler);
        } catch (BusinessException e) {
            logger.error("根据ID查询电脑散热器业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("根据ID查询电脑散热器系统异常", e);
            return Result.error(MessageUtils.getMessage("error.query"));
        }
    }
    
    /**
     * 添加电脑散热器信息
     */
    @PostMapping
    @Operation(summary = "添加电脑散热器信息", description = "向系统中添加新的电脑散热器信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> addPcCooler(
            @Parameter(description = "电脑散热器信息", required = true) @RequestBody PcCooler pcCooler) {
        logger.info("添加电脑散热器请求");
        try {
            // 设置创建时间和更新时间
            pcCooler.setCreatedTime(new Date());
            pcCooler.setUpdatedTime(new Date());
            
            boolean result = pcCoolerService.save(pcCooler);
            if (result) {
                logger.info("添加电脑散热器成功，ID：{}", pcCooler.getId());
                return Result.success(result);
            } else {
                logger.warn("添加电脑散热器失败");
                return Result.error(MessageUtils.getMessage("error.save"));
            }
        } catch (BusinessException e) {
            logger.error("添加电脑散热器业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("添加电脑散热器系统异常", e);
            return Result.error(MessageUtils.getMessage("error.save"));
        }
    }
    
    /**
     * 更新电脑散热器信息
     */
    @PutMapping
    @Operation(summary = "更新电脑散热器信息", description = "更新系统中已有的电脑散热器信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数错误", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到数据", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> updatePcCooler(
            @Parameter(description = "电脑散热器信息", required = true) @RequestBody PcCooler pcCooler) {
        logger.info("更新电脑散热器请求，ID：{}", pcCooler.getId());
        try {
            // 检查数据是否存在
            if (pcCooler.getId() == null || !pcCoolerService.updateById(pcCooler)) {
                logger.warn("更新电脑散热器失败，ID：{}", pcCooler.getId());
                return Result.error(MessageUtils.getMessage("error.update"));
            }
            
            logger.info("更新电脑散热器成功");
            return Result.success(true);
        } catch (BusinessException e) {
            logger.error("更新电脑散热器业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑散热器系统异常", e);
            return Result.error(MessageUtils.getMessage("error.update"));
        }
    }
    
    /**
     * 删除电脑散热器信息
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑散热器信息", description = "从系统中删除指定的电脑散热器信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到数据", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> deletePcCooler(
            @Parameter(description = "电脑散热器ID", required = true, example = "1") @PathVariable Long id) {
        logger.info("删除电脑散热器请求，ID：{}", id);
        try {
            boolean result = pcCoolerService.removeById(id);
            if (result) {
                logger.info("删除电脑散热器成功");
                return Result.success(true);
            } else {
                logger.warn("删除电脑散热器失败，ID：{}", id);
                return Result.error(ErrorEnum.RESOURCE_NOT_FOUND.getCode(), MessageUtils.getMessage("error.notFound"));
            }
        } catch (BusinessException e) {
            logger.error("删除电脑散热器业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑散热器系统异常", e);
            return Result.error(MessageUtils.getMessage("error.delete"));
        }
    }
}